package com.modeler.plugin.handler;

import gatchan.phpparser.parser.PHPParser;
import gatchan.phpparser.parser.ParseException;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import com.prefuse.visualization.PrefuseVisualizationAdapter;

import net.sourceforge.phpdt.internal.compiler.ast.*;

public class ParseSourceCodeHandler extends AbstractHandler {
	private PHPParser parser;

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil
				.getActiveMenuSelection(event);

		Object firstElement = selection.getFirstElement();
		IResource res = (IResource) firstElement;

		String fileLocation = "";
		fileLocation = res.getLocation().toString();

		parsePHPFile(fileLocation);

		Statement[] nodes = parser.getNodes();
		PrefuseVisualizationAdapter prefuseVisualizationAdapter = new PrefuseVisualizationAdapter();
		prefuseVisualizationAdapter.setNodes(nodes);
		prefuseVisualizationAdapter.drawGraph();
		
		return null;
	}

	protected String getPersistentProperty(IResource res, QualifiedName qn) {
		try {
			return res.getPersistentProperty(qn);
		} catch (CoreException e) {
			return "";
		}
	}

	// TODO: Include this in the HTML output

	protected void setPersistentProperty(IResource res, QualifiedName qn,
			String value) {
		try {
			res.setPersistentProperty(qn, value);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

	private void parsePHPFile(String path) {
		parser = new PHPParser();
		try {
			String fileAsString = "";
			try {

				fileAsString = readFileAsString(path);
			} catch (IOException e) {
				MessageDialog.openInformation(null, "File not found!", e
						.getMessage());
			}
			parser.parse(fileAsString);
		} catch (ParseException e) {
			MessageDialog.openInformation(null,
					"Parser could not be successful", e.getMessage());
		}
		
		
	}

	private String readFileAsString(String filePath) throws IOException {
		StringBuffer fileData = new StringBuffer();
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
		}
		reader.close();
		return fileData.toString();
	}

}